/**
 * Created by Ethan.Yang on 2016/8/22.
 * Changed by Guang Li on 2016/8/22.
 */
define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'model/testData', 'model/project',
        'stringUtils', 'common/widgetUtils', 'common/mathUtils', 'model/tolerance',
        'business/socket/socketBiz', 'appMessageBox', 'dateUtils', 'd3/d3-main', 'datetimepicker/datetimepicker', 'jeditable/jquery.jeditable'],
    function ($, domReady, appLocalStorage, appConst, globalM, testDataM, projectM, stringUtils, widgetUtils, mathUtils, toleranceM, socketBiz, msgBox, dateUtils) {
        var searchFields = {};
        var components = {};
        var data = {
            projectDS: [],
            dcDS: [],
            toleranceItemDS: [],
            custom: {
                digit: 6,
                search_timeout_key_spc: "",
            },
            importFiles: [],
            ws: {
                sockjs: null,
                stomp: null
            },
            rowSize: null
        };
        var that;

        var searchBarKey = {
            "fields": "searchbar.search.fields",
            "ds": "searchbar.search.ds"
        };
        var listeners = {
            'initCompleted': function () {
            }
        };
        var isRead = {
            project: true,
            dc: true,
            allTrue: function () {
                isRead.project = true;
                isRead.dc = true;
            }
        };

        function getFileNameFromPath(filePath) {
            var path = filePath;
            var pos1 = path.lastIndexOf('/');
            var pos2 = path.lastIndexOf('\\');
            var pos = Math.max(pos1, pos2);
            var fileName = pos < 0 ? path : path.substring(pos + 1);
            return fileName;
        }

        return {
            init: function () {
                that = this;
                // data.search_timeout_key_spc = appConst.searchKey.search_dataImport_timeout_key + global.getUserId();
                components = {
                    wgt_chart: $('#wgt_chart'),
                    "project": $('#searchbar').find('#slt_sb_project'),
                    "dc": $('#searchbar').find("#slt_sb_dc"),
                    "searchBtn": $('#searchbar').find('#btn_sb_searchBtn'),
                    "toleranceItem": $('#tbl_tolerance_item'),
                    "alt_sb_searchAlert": $('#searchbar').find('#alt_sb_searchAlert'),
                    "dlg_tolerance_new": $('#dlg_tolerance_new'),
                    "slt_tolerance_new_project": $('#slt_tolerance_new_project'),
                    "slt_tolerance_new_name": $('#slt_tolerance_new_name'),
                    "tolerance_usl": $('#tolerance_usl'),
                    "tolerance_lsl": $('#tolerance_lsl'),
                    "tolerance_calculateTimes": $('#tolerance_calculateTimes'),
                    "spn_ndc_yeild": $('#spn_ndc_yeild'),
                    "btn_tolerance_new_submit": $('#btn_tolerance_new_submit'),
                    "alt_tolerance_new_msgbar": $('#alt_tolerance_new_msgbar'),
                    "toleranceItem_name": $('#toleranceItem_name'),
                    "itemNameSubmit": $('#itemNameSubmit'),
                    "btn_runTolerance": $('#btn_runTolerance'),
                    "btn_tolerance_new_cancel": $('#btn_tolerance_new_cancel'),

                    toleranceChart_NDC: $('#toleranceChart_NDC'),

                    wzd_tolerance_import: $('#wzd_tolerance_import'),
                    dlg_tolerance_import: $('#dlg_tolerance_import'),
                    slt_tolerance_import_project: $('#slt_tolerance_import_project'),
                    slt_tolerance_import_dc: $('#slt_tolerance_import_dc'),
                    spn_tolerance_import_processbar: $('#spn_tolerance_import_processbar'),
                    spn_tolerance_import_logArea: $('#spn_tolerance_import_logArea'),
                    spn_tolerance_import_status: $('#spn_tolerance_import_status'),
                    btn_tolerance_import_submit: $('#btn_tolerance_import_submit'),
                    fle_tolerance_import_file: $('#fle_tolerance_import_file'),
                    btn_tolerance_import_gobackTo1: $('#btn_tolerance_import_gobackTo1'),
                    spn_tolerance_import_time: $('#spn_tolerance_import_time'),
                    alt_tolerance_import_msgbar: $('#alt_tolerance_import_msgbar'),
                    div_tolerance_import_upload_files: $('#div_tolerance_import_upload_files'),
                    txt_tolerance_import_soltkey: $('#txt_tolerance_import_soltkey'),
                    btn_tolerance_export: $('#btn_tolerance_export')
                };
                isRead.allTrue();
                that.initProject();
                that.initDc();
                that.bindSearchEvent();
                that.reloadProject(function () {
                    that.matchLocalSearchFieldData();
                    listeners.initCompleted();
                });
                that.initDimensionChainPanel();
                that.initCreateDimensionModalDialog();

                that.bindSearchEvent();

                that.initImportModalDialog();
                //that.loadChart();
                //that.buildNDChart();
                that.bindRunEvent();
                that.bindExportEvent()

            },
            initProject: function (callback) {
                data.projectDS = [];
                components.project.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.projectDS, text: 'name'};
                    },
                    formatResult: function (data) {
                        var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (data) {
                        return data.name == null ? '' : data.name;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.project.on('change', function (e) {

                    components.dc.select2("val", "").trigger("change");
                    ;
                    data.dcDS = [];

                    that.reloadDc();
                });
            },
            reloadProject: function (callback) {
                data.projectDS = [];
                projectM.searchProject(null, function (d) {
                    if (d == null) {
                        return;
                    }
                    data.projectDS = d;
                    if (isRead.project == true) {
                        var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);
                        if (localSearchFields != null) {
                            var localsf = JSON.parse(localSearchFields);
                            components.project.select2("val", localsf.search_projectId).trigger("change");
                        }
                        isRead.project = false;
                    }
                    callback();
                });

            },
            initDc: function (callback) {
                data.dcDS = [];
                components.dc.select2({
                    id: function (r) {
                        return r.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.dcDS, text: 'name'};
                    },
                    formatResult: function (data) {
                        var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (data) {
                        return data.name == null ? '' : data.name;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.dc.on('change', function (e) {
                    components.toleranceChart_NDC.empty();
                    components.btn_tolerance_export.prop('disabled', true);
                    components.toleranceItem.dataTable().fnClearTable();
                    document.getElementById("tolerance_usl").value = "";
                    document.getElementById("tolerance_lsl").value = "";
                    document.getElementById("tolerance_calculateTimes").value = "";
                    $('#spn_ndc_yeild').empty().html("-%");
                    components.btn_runTolerance.prop("disabled", true);
                    components.itemNameSubmit.prop("disabled", true);
                });
            },
            reloadDc: function (callback) {
                data.dcDS = [];
                var pm = {
                    projectId: components.project.select2('val')
                };
                if (stringUtils.isBlank(pm.projectId)) {
                    return;
                }
                toleranceM.searchDc(pm, function (d) {
                    if (d == null) {
                        return;
                    }
                    data.dcDS = d;
                    if (isRead.dc == true) {
                        var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);

                        if (localSearchFields != null) {
                            var localsf = JSON.parse(localSearchFields);
                            if (localsf.search_projectId != pm.projectId) {
                                localsf.search_dcIds = [];
                                appLocalStorage.setLocal(searchBarKey.fields, JSON.stringify(localsf));
                            } else {
                                components.dc.select2("val", localsf.search_dcIds).trigger("change");
                            }
                        }
                        isRead.dc = false;
                    }
                });
            },
            loadSetting: function (callback) {
                var dc = components.dc.select2('val');
                var pm = {
                    projectId: components.project.select2('val')
                };
                if (stringUtils.isBlank(pm.projectId)) {
                    return;
                }
                if (stringUtils.isBlank(dc)) {
                    return;
                }
                toleranceM.searchDc(pm, function (d) {
                    if (d == null) {
                        return;
                    }
                    for (var i = 0; i < d.length; i++) {
                        if (d[i].id == dc) {
                            document.getElementById("tolerance_usl").value = d[i].usl;
                            document.getElementById("tolerance_lsl").value = d[i].lsl;
                            document.getElementById("tolerance_calculateTimes").value = d[i].calculateTimes;
                            break;
                        }
                    }
                });
            },
            bindSearchEvent: function (listener) {
                components.searchBtn.unbind('click');
                components.searchBtn.click(function (e) {
                    components.toleranceChart_NDC.empty();
                    components.alt_sb_searchAlert.fadeOut(200);
                    if (components.project.select2('data') == null) {
                        document.getElementById("warn-label").innerHTML = $.i18n.prop("EXCEPTION_GLOBAL_PROJECT");
                        components.alt_sb_searchAlert.fadeIn(200);
                        return;
                    }
                    if (components.dc.select2('data') == null) {
                        document.getElementById("warn-label").innerHTML = $.i18n.prop("EXCEPTION_GLOBAL_DIMENSIONCHAIN");
                        components.alt_sb_searchAlert.fadeIn(200);
                        return;
                    }
                    that.setConditionsToLocalStorage();
                    that.loadSetting();
                    that.loadToleranceItemData();
                    if ((typeof listener) == 'function') {
                        listener(searchFields);
                    }
                });
            },
            onCompleted: function (listener) {
                if (typeof listener == "function") {
                    listeners.initCompleted = listener;
                }
            },
            doSearch: function () {
                components.searchBtn.trigger("click");
            },
            matchLocalSearchFieldData: function () {
                var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);
            },
            getSearchParameters: function () {
                var searchParam = {
                    'search_projectId': components.project.select2('val'),
                    'search_dcIds': components.dc.select2('val'),
                };
                searchFields = searchParam;
                return searchParam;
            },
            setConditionsToLocalStorage: function (key) {
                var searchParam = that.getSearchParameters();
                appLocalStorage.setLocal(searchBarKey.fields, JSON.stringify(searchParam));

                var localDS = {
                    dcDS: data.dcDS,
                };
                appLocalStorage.setLocal(searchBarKey.ds, JSON.stringify(localDS));
            },
            getSearchFields: function () {
                return searchFields;
            },
            getCurrentChoiceProjectId: function () {
                return components.project.select2('val');
            },
            getProjectDS: function () {
                return data.projectDS;
            },
            getLocalStorageDS: function () {
                var localSearchFields = appLocalStorage.getLocal(searchBarKey.ds);
                var localsf = JSON.parse(localSearchFields);
                return localsf;
            },

            //ToleranceItem Data panel
            initDimensionChainPanel: function () {
                that.initToleranceItemTable();
            },
            initToleranceItemTable: function () {
                data.toleranceItemDS = [];
                components.toleranceItem.dataTable({
                    "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                    "processing": true,
                    "ordering": false,
                    "paging": true,
                    "lengthChange": false,
                    "pageLength": 50,
                    "searching": true,
                    "language": appConst.table_language(),
                    "bFilter": false,
                    "ajax": {
                        "url": "empty",
                        "type": "POST",
                        "dataSrc": "body",
                        "traditional": true,
                        "data": that.getSchemeParameter,

                        "error": function (e) {
                            if (e.status == 401) {
                                msgBox.sessionFailureBox();
                            }
                            if (e.status == 500) {
                                msgBox.serverFailureBox();
                            }
                            if (e.status == 404) {
                                msgBox.pathFailureBox();
                            }
                        }
                    },
                    "columns": [
                        {"data": "code"},
                        {"data": "id"},
                        {"data": "componentName"},
                        {"data": "loopType"},
                        {"data": "coefficient"},
                        {"data": "nominalSize"},
                        {"data": "unilateralTolerance"},
                        {"data": "ldl"},
                        {"data": "udl"},
                        {"data": "mean"},
                        {"data": "sigma"},
                        {"data": null}
                    ],
                    "columnDefs": [
                        {
                            "targets": [0],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'code').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [1],
                            "visible": false,
                            "searchable": false
                        },
                        {
                            "targets": [2],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'componentName').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [3],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'loopType').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [4],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'coefficient').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [5],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'nominalSize').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [6],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'unilateralTolerance').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [7],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'ldl').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [8],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'udl').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [9],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'mean').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [10],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('type', 'sigma').attr('dataId', rowData.id).attr('row', row);
                            }
                        },
                        {
                            "targets": [11],
                            "render": function (data, type, full) {
                                var id = full.id;
                                if (id == "") {
                                    var operate = "<a href='javascript:void(0);' class='saveItem'  > Save</a>   " +
                                        "<a href='javascript:void(0);' class='deleteItem' id='" + id + "' >" + $.i18n.prop("GLOBAL_DELETE") + "</a>";
                                } else {
                                    var operate = "<a href='javascript:void(0);' class='deleteItem' id='" + id + "' >" + $.i18n.prop("GLOBAL_DELETE") + "</a>";
                                }

                                return operate;
                            }
                        }
                    ],
                    "drawCallback": function (settings) {
                        var api = this.api();
                        $('#tbl_tolerance_item tbody td.inputTd').jeditable(
                            function (value, settings) {
                                var cell = api.cell(this);
                                cell.data(value);
                                var id = $(this).attr("dataId");
                                var param = that.getItemParameters();
                                var row = parseInt($(this).attr('row'));

                                var t = components.toleranceItem.dataTable();
                                var nTrs = t.fnGetNodes();

                                param.code = t.fnGetData(nTrs[row]).code;
                                param.id = id;
                                param.componentName = t.fnGetData(nTrs[row]).componentName;
                                param.loopType = t.fnGetData(nTrs[row]).loopType;
                                param.coeffiecient = t.fnGetData(nTrs[row]).coeffiecient;
                                param.nominalSize = t.fnGetData(nTrs[row]).nominalSize;
                                param.unilateralTolerance = t.fnGetData(nTrs[row]).unilateralTolerance;
                                param.ldl = t.fnGetData(nTrs[row]).ldl;
                                param.udl = t.fnGetData(nTrs[row]).udl;
                                param.mean = t.fnGetData(nTrs[row]).mean;
                                param.sigma = t.fnGetData(nTrs[row]).sigma;

                                if (id != "") {
                                    toleranceM.updateItem(param);
                                }
                            }, {
                                height: '15',
                                width: '80',
                                cssclass: 'smart-form',
                                placeholder: '',
                                onsubmit: function (settings, original) {
                                    var dataid = $(original).attr("dataid");
                                    if (dataid != "") {
                                        var type = $(original).attr("type");
                                        if (type == "nominalSize") {
                                            $(this).validate({
                                                errorPlacement: function (error, element) {
                                                    var form = $(element).parent();
                                                    form.next().remove();
                                                    form.parent().append(error);
                                                },
                                                success: function (error, element) {
                                                    var form = $(element).parent();
                                                    form.next().remove();
                                                },
                                                rules: {
                                                    value: {required: !0, number: true, maxlength: 20}
                                                },
                                                messages: {
                                                    value: {
                                                        required: $.i18n.prop("WARINING_ITEM_NOTEMPTY"),
                                                        number: $.i18n.prop("EXCEPTION_GLOBAL_NOT_NUMBER"),
                                                        maxlength: $.i18n.prop("WARINING_ITEM_LONG")
                                                    }
                                                }
                                            });
                                            return $(this).valid();
                                        }
                                        if (type == "sigma") {
                                            jQuery.validator.addMethod("issigma", function (value, element) {
                                                var sigma = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
                                                return this.optional(element) || (sigma.test(value));
                                            }, $.i18n.prop("EXCEPTION_GLOBAL_SIGMA_NUMBER"));
                                            $(this).validate({
                                                errorPlacement: function (error, element) {
                                                    var form = $(element).parent();
                                                    form.next().remove();
                                                    form.parent().append(error);
                                                },
                                                success: function (error, element) {
                                                    var form = $(element).parent();
                                                    form.next().remove();
                                                },
                                                rules: {
                                                    value: {required: !0, issigma: true, maxlength: 20}
                                                },
                                                messages: {
                                                    value: {
                                                        required: $.i18n.prop("WARINING_ITEM_NOTEMPTY"),
                                                        maxlength: $.i18n.prop("WARINING_ITEM_LONG")
                                                    }
                                                }
                                            });
                                            return $(this).valid();
                                        }
                                    }

                                        $(this).validate({
                                            errorPlacement: function (error, element) {
                                                var form = $(element).parent();
                                                form.next().remove();
                                                form.parent().append(error);
                                            },
                                            success: function (error, element) {
                                                var form = $(element).parent();
                                                form.next().remove();
                                            },
                                            rules: {
                                                value: {maxlength: 20}
                                            },
                                            messages: {
                                                value: {
                                                    maxlength: $.i18n.prop("WARINING_ITEM_LONG"),
                                                }
                                            }
                                        });
                                        return $(this).valid();


                                }
                            });
                        components.toleranceItem.find(".deleteItem").unbind("click").on("click", function () {
                            var id = $(this).attr("id");
                            if (id != "") {
                                that.deleteMsg(id);
                            } else {
                                var t = components.toleranceItem.DataTable();
                                t.row($(this).parents('tr')).remove().draw();

                            }
                        });

                        components.toleranceItem.find(".saveItem").unbind("click").on("click", function () {
                            var param = that.getItemParameters();

                            var row = parseInt($(this).parents('tr').children().attr('row'));
                            var t = components.toleranceItem.dataTable();
                            var nTrs = t.fnGetNodes();

                            param.code = t.fnGetData(nTrs[row]).code;
                            param.componentName = t.fnGetData(nTrs[row]).componentName;
                            param.loopType = t.fnGetData(nTrs[row]).loopType;
                            param.coeffiecient = t.fnGetData(nTrs[row]).coeffiecient;
                            param.nominalSize = t.fnGetData(nTrs[row]).nominalSize;
                            param.unilateralTolerance = t.fnGetData(nTrs[row]).unilateralTolerance;
                            param.ldl = t.fnGetData(nTrs[row]).ldl;
                            param.udl = t.fnGetData(nTrs[row]).udl;
                            param.mean = t.fnGetData(nTrs[row]).mean;
                            param.sigma = t.fnGetData(nTrs[row]).sigma;

                            if (param.nominalSize == "" || param.sigma == "") {
                                msgBox.errorBox("EXCEPTION_GLOBAL_OBJECT_ISNULL", "PARAM_SAVE_VALUE");
                                return false;
                            }
                            var regExp = /^[+-]?\d+(\.\d+)?$/;
                            if (!regExp.test(param.nominalSize)) {
                                msgBox.errorBox("EXCEPTION_GLOBAL_NOT_NUMBER");
                                return false;
                            }
                            var regExp1 = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
                            if (!regExp1.test(param.sigma)) {
                                msgBox.errorBox("EXCEPTION_GLOBAL_SIGMA_NUMBER");
                                return false;
                            }
                            toleranceM.addItemName(param, function (d) {
                                that.loadToleranceItemData();
                            });
                        });
                    }
                });
                components.toleranceItem.DataTable().on('draw.dt', function () {
                    var dt = $(this).dataTable();
                    dt.api().column(1, {draw: 'applied'}).nodes().each(function (cell, i) {
                        var pageNum = dt.api().page();
                        var pageSize = dt.api().page.len();
                        cell.innerHTML = pageNum * pageSize + i + 1;
                        data.rowSize = i;
                    });
                });

                components.itemNameSubmit.on('click', function (e) {
                    var t = components.toleranceItem.DataTable();
                    var itemName = components.toleranceItem_name.val();
                    var t1 = components.toleranceItem.dataTable();
                    var nTrs = t1.fnGetNodes();
                    if (t1.fnGetData(nTrs[data.rowSize]).id != "") {
                        components.toleranceItem_name.parent().removeClass("state-error");
                        components.toleranceItem_name.parent().addClass("state-success");
                        document.getElementById("add-label").innerHTML = "";
                        var rowNode = t.row.add({
                            "code": itemName,
                            "id": "",
                            "componentName": "",
                            "loopType": "",
                            "coefficient": "",
                            "nominalSize": "",
                            "unilateralTolerance": "",
                            "udl": "",
                            "ldl": "",
                            "mean": "",
                            "sigma": "",
                            }
                        ).draw().node();
                    } else {
                        components.toleranceItem_name.parent().removeClass("state-success");
                        components.toleranceItem_name.parent().addClass("state-error");
                        document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_SAVE_EXISTS") + "</font>";
                    }
                });
                components.toleranceItem_name.on('click',function (e) {
                    if (document.getElementById("add-label").innerHTML != "") {
                        components.toleranceItem_name.parent().removeClass("state-error");
                        components.toleranceItem_name.parent().addClass("state-success");
                        document.getElementById("add-label").innerHTML = "";
                    }
                });


            },
            loadToleranceItemData: function (d) {
                components.toleranceItem.DataTable().ajax.url("analysis/tolerance/getItem").load(function () {
                    components.btn_runTolerance.prop("disabled", false);
                    components.itemNameSubmit.prop("disabled", false);
                    if (typeof callback == 'function') {
                        callback();
                    }
                });
            },
            deleteMsg: function (id) {
                msgBox.show({
                    title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                    content: "" + $.i18n.prop("ITEM_DELETE_SUBMIT") + " <p class='text-align-right'>" +
                    "<button type='submit' class='btn btn-primary btn-sm deleteitem" + id + "'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                    "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                    type: 'normal',
                    timeout: false,
                    clean: true
                });
                $('#divSmallBoxes').find('.deleteitem' + id).unbind('click').on('click', function (e) {
                    var param = {
                        "id": id
                    }
                    toleranceM.deleteItem(param, function (d) {
                        that.loadToleranceItemData();
                    });
                });
            },
            getItemParameters: function () {
                var param = {
                    'projectId': components.project.select2('val'),
                    'schemeId': components.dc.select2('val'),
                };
                return param;
            },
            getSchemeParameter: function () {
                var param = {
                    'search_dcIds': components.dc.select2('val')
                };
                return param;
            },

            //Create New DimensionChain
            initCreateDimensionModalDialog: function () {
                components.slt_tolerance_new_project.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.projectDS, text: 'name'};
                    },
                    formatResult: function (data) {
                        var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (data) {
                        return data.name == null ? '' : data.name;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_tolerance_new_project.on('change', function (e) {

                });

                components.dlg_tolerance_new.on('show.bs.modal', function (e) {

                    data.projectDS = that.getProjectDS();
                    var projectId = that.getCurrentChoiceProjectId();
                    components.slt_tolerance_new_project.select2("val", projectId);
                });

                components.dlg_tolerance_new.on('hide.bs.modal', function (e) {
                    if (components.slt_tolerance_new_project.select2('val') == that.getCurrentChoiceProjectId()) {
                        that.reloadDc();
                    }

                });
                components.btn_tolerance_new_submit.click(function (e) {
                    components.alt_tolerance_new_msgbar.fadeOut(200);
                    if (components.slt_tolerance_new_project.select2('val') == "") {
                        document.getElementById("create-label").innerHTML = $.i18n.prop("CREATE_ERR_PROJECT");
                        components.alt_tolerance_new_msgbar.fadeIn(200);
                        return;
                    }

                    if (components.slt_tolerance_new_name.val() == "") {
                        document.getElementById("create-label").innerHTML = $.i18n.prop("CREATE_ERR_MSG");
                        components.alt_tolerance_new_msgbar.fadeIn(200);
                        return;
                    }

                    that.loadCreateDimensionChain();


                });

            },
            loadCreateDimensionChain: function () {
                var param = that.getCreateParameters();
                toleranceM.createDimensionChain(param, function (d) {
                    components.btn_tolerance_new_cancel.trigger("click");
                });
            },
            getCreateParameters: function () {
                var searchParam = {
                    'projectId': components.slt_tolerance_new_project.select2('val'),
                    'name': components.slt_tolerance_new_name.val(),
                };

                searchFields = searchParam;
                return searchParam;
            },

            //Run Chart
            bindRunEvent: function (listener) {
                components.btn_runTolerance.unbind('click');
                components.btn_runTolerance.click(function (e) {
                    var param = that.getSchemeParameters();
                    if (param.usl == "" || param.lsl == "" || param.calculateTimes == "") {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_EMPTY") + "</font>";
                        return;
                    }
                    var regExp = /^[+-]?\d+(\.\d+)?$/;
                    if (!regExp.test(param.usl) || !regExp.test(param.lsl)) {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_INTEGER") + "</font>";
                        return;
                    }
                    if (parseFloat(param.usl) <= parseFloat(param.lsl)) {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_USL_LSL") + "</font>";
                        return;
                    }
                    var regExp1 = /^(0|\+?[1-9][0-9]*)$/;
                    if (!(regExp1.test(param.calculateTimes))) {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_POSITIVE_INTEGER") + "</font>";
                        return;
                    }
                    that.loadChart(param);
                    if ((typeof listener) == 'function') {
                        listener(searchFields);
                    }
                });
                components.tolerance_usl.on('click', function (e) {
                    if(document.getElementById("param-label").innerHTML != ""){
                        document.getElementById("param-label").innerHTML = "";
                    }
                });
                components.tolerance_lsl.on('click', function (e) {
                    if(document.getElementById("param-label").innerHTML != ""){
                        document.getElementById("param-label").innerHTML = "";
                    }
                });
                components.tolerance_calculateTimes.on('click', function (e) {
                    if(document.getElementById("param-label").innerHTML != ""){
                        document.getElementById("param-label").innerHTML = "";
                    }
                });
            },
            getSchemeParameters: function () {
                var searchParam = {
                    'projectId': components.project.select2('val'),
                    'schemeId': components.dc.select2('val'),
                    'usl': components.tolerance_usl.val(),
                    'lsl': components.tolerance_lsl.val(),
                    'calculateTimes': components.tolerance_calculateTimes.val(),
                };

                searchFields = searchParam;
                return searchParam;
            },
            loadChart: function (param) {
                components.toleranceChart_NDC.empty();
                widgetUtils.toggleGridLoading(components.wgt_chart, 'loading');
                toleranceM.analyseNDC(param, function (d) {
                    if (d == null || d == "") {
                        components.toleranceChart_NDC.empty();
                        widgetUtils.toggleGridLoading(components.wgt_chart, true);
                        return;
                    }
                    if (d.result == null) {
                        components.toleranceChart_NDC.empty();
                        widgetUtils.toggleGridLoading(components.wgt_chart, true);
                        return
                    }
                    components.btn_tolerance_export.prop('disabled', false);
                    $('#spn_ndc_yeild').empty().html(d.result != null ? mathUtils.round(d.result * 100, 4) + "%" : '-');
                    that.buildNDChart(d.normalDistributionDto);
                    widgetUtils.toggleGridLoading(components.wgt_chart, true);
                }, function () {
                    widgetUtils.toggleGridLoading(components.wgt_chart, true);
                })
            },
            buildNDChart: function (d) {
                components.toleranceChart_NDC.empty();
                var chartObj = d3.select('#toleranceChart_NDC');
                var barDataArray = d3.zip(d.histogramDataObj.divideValueAry, d.histogramDataObj.pointCountAry);
                var lcl = d.ndsDataItem.lclValue;
                var ucl = d.ndsDataItem.uclValue;
                var lsl = d.staDataItem.lslValue;
                var usl = d.staDataItem.uslValue;
                var stdValue = d.ndsDataItem.stdValue;
                var avgValue = d.ndsDataItem.avgValue;
                var ucl2lcl = ucl - lcl;
                var barX = d.histogramDataObj.divideValueAry;

                var lineset = new Array();
                lineset.push({data: lcl, color: fillcolor.red, name: 'LCL'});
                lineset.push({data: ucl, color: fillcolor.red, name: 'UCL'});
                lineset.push({data: avgValue, color: fillcolor.degreen, name: 'C'});
                lineset.push({data: avgValue - stdValue, color: fillcolor.green, name: '-σ'});
                lineset.push({data: avgValue + stdValue, color: fillcolor.green, name: 'σ'});
                lineset.push({data: avgValue - 2 * stdValue, color: fillcolor.green, name: '-2σ'});
                lineset.push({data: avgValue + 2 * stdValue, color: fillcolor.green, name: '2σ'});

                var cellOffset = 0;
                for (var i = 0, n = barDataArray.length, bin; i < n; i++) {
                    bin = barDataArray[i];
                    if (i == 0) {
                        bin.offset = 0;
                    }
                    else {
                        bin.offset = barDataArray[i - 1][0];
                    }
                    bin.width = bin[0] - bin.offset;
                    cellOffset = bin.width;
                    bin.height = bin[1];
                }
                barDataArray.shift();

                var slArray = new Array();
                slArray.push(lcl);
                slArray.push(ucl);

                if (usl != null) {
                    if (usl <= (ucl + ucl2lcl)) {
                        slArray.push(usl);
                        lineset.push({data: usl, color: fillcolor.degreen, name: 'USL'});
                    }
                }
                if (lsl != null) {
                    if (lsl >= (lcl - ucl2lcl)) {
                        slArray.push(lsl);
                        lineset.push({data: lsl, color: fillcolor.degreen, name: 'LSL'});
                    }
                }

                var allDataForX = d3.merge([d.histogramDataObj == null ? [] : d.histogramDataObj.divideValueAry,
                    slArray, d.curveDataObj == null ? [] : d.curveDataObj.xvalueAry]);
                allDataForX.push(d3.min(allDataForX) - cellOffset);
                allDataForX.push(d3.max(allDataForX) + cellOffset);

                var heightValue = 400;
                var margin = {top: 5, right: 30, bottom: 30, left: 70};
                var width = components.toleranceChart_NDC.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var xBarMax = d3.max(barX);
                var xBarMin = d3.min(barX);
                var xMax = d3.max(allDataForX);
                var xMin = d3.min(allDataForX);
                var yMax = d3.max(d.histogramDataObj.pointCountAry, function (d) {
                    return d;
                });

                var x = d3.scale.linear()
                    .domain([xMin, xMax])
                    .range([0, width]);

                var yUlimit = yMax + Math.ceil(yMax / 10);


                var y = d3.scale.linear()
                    .domain([0, yUlimit])
                    .range([height, 0]);

                var ry = d3.scale.linear()
                    .domain([0, d3.max(d.curveDataObj == null ? [] : d.curveDataObj.yvalueAry)])
                    .range([height, 15]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .tickSize(0, -height)
                    .tickPadding(8);


                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(d3.format("C"))
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8);

                var ryAxis = d3.svg.axis()
                    .scale(ry)
                    .orient("right")
                    .ticks(5)
                    .tickFormat(d3.format("C"))
                    .tickSize(0, 0)
                    .tickPadding(8);

                var barTip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (d) {
                            return "<strong>Count:</strong> <span>" + d[1] + "</span><br/><span><strong>X:</strong> [" + mathUtils.round(d.offset, data.custom.digit) + " - " + mathUtils.round(d[0], data.custom.digit) + "]</span>";
                        }
                    );

                var cycTip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (d) {
                        return "<strong>" + d[0] + ",</strong> <span>" + d[1] + "</span>";
                    });

                chartObj.selectAll('g.bar').remove();

                var svg = chartObj
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom);

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .attr("transform", "translate(" + width + ",0)")
                    .call(ryAxis);

                drawChart(container);
                function drawChart(p) {
                    var barwidth = (x(xBarMax) - x(xBarMin)) / (barX.length - 1);
                    p.selectAll('.line').remove();
                    p.selectAll('text.linetext').remove();
                    p.selectAll('g.bars').remove();
                    p.selectAll('path.curveline').remove();

                    p.append('g')
                        .call(barTip)
                        .attr('class', 'bars')
                        .selectAll("rect")
                        .data(barDataArray)
                        .enter().append("rect")
                        .attr("class", "bar")
                        .attr("x", function (da, i) {
                            return x(da.offset);
                        })
                        .attr("width", function (da) {
                            return barwidth;
                        })
                        .attr("y", function (da) {
                            return y(da.height);
                        })
                        .attr("height", function (da) {
                            return height - y(da.height);
                        })
                        .attr('style', "fill:#3276B1;")
                        .on('mouseover', function (da, i) {
                            d3.select(this).style('fill', fillcolor.blue);
                            barTip.show(da);
                        })
                        .on('mouseout', function (da, i) {
                            d3.select(this).transition().duration(250).style('fill', '#3276B1');
                            barTip.hide();
                        });

                    p.selectAll('.line')
                        .data(lineset)
                        .enter().append("line")
                        .attr('class', 'line')
                        .attr('x1', function (da) {
                            return x(da.data);
                        })
                        .attr('x2', function (da) {
                            return x(da.data);
                        })
                        .attr('y1', function (da) {
                            return 12;
                        })
                        .attr('y2', function (da) {
                            return height;
                        })
                        .attr('stroke', function (da) {
                            return da.color;
                        })
                        .attr('stroke-width', '2')
                        .attr('style', 'clip-path: url(#clip);');

                    p.selectAll(".linetext")
                        .data(lineset)
                        .enter().append("text")
                        .text(function (d) {
                            return d.name;
                        })
                        .attr('class', 'linetext')
                        .attr("text-anchor", "middle")
                        .attr("x", function (da, i) {
                            return x(da.data);
                        })
                        .attr("y", function (da) {
                            return 10;
                        })
                        .attr("font-size", "11px")
                        .attr("fill", function (da) {
                            return da.color;
                        })
                        .attr('style', ' clip-path: url(#clip);');

                    var curveDataLine = d3.svg.line()
                        .x(function (da) {
                            return x(da[0]);
                        })
                        .y(function (da) {
                            return ry(da[1]);
                        });

                    var rPathData = d3.zip(d.curveDataObj == null ? [] : d.curveDataObj.xvalueAry, d.curveDataObj == null ? [] : d.curveDataObj.yvalueAry);

                    p.append("path")
                        .attr("class", "curveline")
                        .attr("style", "fill: none;stroke: brown;stroke-width: 1.5px;")
                        .attr("d", curveDataLine(rPathData))
                }
            },

            //Import modal dialog
            initImportModalDialog: function () {
                var wizard = components.wzd_tolerance_import;
                wizard.wizard('selectedItem', {
                    step: 1
                });

                components.slt_tolerance_import_project.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.projectDS, text: 'name'};
                    },
                    formatResult: function (data) {
                        var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (data) {
                        return data.name == null ? '' : data.name;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_tolerance_import_project.on('change', function (e) {
                });

                components.dlg_tolerance_import.on('show.bs.modal', function (e) {
                    that.cleanSocket();
                    that.initSocket();

                    data.projectDS = that.getProjectDS();
                    data.importFiles = [];
                    components.div_tolerance_import_upload_files.empty();
                    var projectId = that.getCurrentChoiceProjectId();
                    wizard.wizard('selectedItem', {
                        step: 1
                    });
                    components.slt_tolerance_import_project.select2("val", that.getCurrentChoiceProjectId());
                    that.cleanImportDialogForm();
                    that.cleanImportDialogProcess();
                });
                components.dlg_tolerance_import.on('hide.bs.modal', function (e) {
                    that.cleanSocket();
                    if (components.slt_tolerance_import_project.select2('val') == that.getCurrentChoiceProjectId()) {
                        that.reloadDc();
                        //dc = components.slt_tolerance_import_dc.val();
                        //that.doSearch();
                    }
                });

                components.btn_tolerance_import_submit.on('click', function (e) {
                    if (data.importFiles.length == 0) {
                        components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-warning").html($.i18n.prop('DATAIMPORT_ERR_MSG')).fadeIn(200);
                        return false;
                    }

                    var isCsv = true;
                    $.each(data.importFiles, function (i, obj) {
                        var fileTypes = ["xlsx","xls"];
                        var fileType = obj.name.substring(obj.name.lastIndexOf('.') + 1);
                        if ($.inArray(fileType.toLocaleLowerCase(), fileTypes) == -1) {
                            components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-warning").html($.i18n.prop('DATAIMPORT_ERR_MSG')).fadeIn(200);
                            isCsv = false;
                            return false;
                        }
                    });
                    if (isCsv == false) {
                        return false;
                    }
                    var param = {
                        'project' : components.slt_tolerance_import_project.select2('val'),
                        'dc' : components.slt_tolerance_import_dc.val(),
                    }
                    if (param.project == "") {
                        components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-warning").html($.i18n.prop('DATAIMPORT_ERR_MSG')).fadeIn(200);
                        return false;
                    }
                    if (param.dc == "") {
                        components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-warning").html($.i18n.prop('DATAIMPORT_TOLERANCE_ERR_MSG')).fadeIn(200);
                        return false;
                    }
                    toleranceM.isExist(param, function (d) {
                        if (d == false) {
                            components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-warning").html($.i18n.prop('DATAIMPORT_TOLERANCE_ERR_MSG')).fadeIn(200);
                            return false;
                        }
                    })
                    function timedCount(c) {
                        var time = dateUtils.second_to_date(c);
                        components.spn_tolerance_import_time.html(time);

                        var timeout = setTimeout(function () {
                            timedCount(c + 1);
                        }, 1000);
                        var obj = {timeout: timeout};
                        appLocalStorage.setLocal(data.search_timeout_key_spc, JSON.stringify(obj));
                    }
                    that.checkImportFile(function (d) {
                        if (d == true) {
                            components.alt_tolerance_import_msgbar.removeClass("alert-warning", "alert-danger").addClass("alert-danger").html("The file is already exists in the server.").fadeIn(200);
                        } else {
                            var fileForm = $('#frm_tolerance_import');
                            fileForm.attr("action", 'analysis/tolerance/import');
                            fileForm.submit();

                            wizard.wizard('selectedItem', {
                                step: 3
                            });

                            components.btn_tolerance_import_submit.hide();
                            components.btn_tolerance_import_gobackTo1.show();
                            that.cleanImportDialogProcess();
                            timedCount(0);
                        }
                    });

                });

                components.btn_tolerance_import_gobackTo1.on('click', function (e) {
                    wizard.wizard('selectedItem', {
                        step: 1
                    });

                    that.cleanSocket();
                    that.initSocket();
                    $(this).hide();
                    that.cleanImportDialogProcess();
                    components.btn_tolerance_import_submit.show();
                });

                components.fle_tolerance_import_file.on("change", function (e) {
                    components.alt_tolerance_import_msgbar.hide();
                    var files = e.target.files;
                    data.importFiles = [];

                    $.each(files, function (i, obj) {
                        data.importFiles.push(files[i]);
                    });

                    function drawFileList(fs) {
                        components.div_tolerance_import_upload_files.empty();
                        for (var i = 0; i < fs.length; i++) {
                            var fileName = fs[i].name;
                            var fileSize = mathUtils.round(fs[i].size / (1000 * 1000), 2) + "M";
                            components.div_tolerance_import_upload_files.append("<div class='txt-color-blue'>" + fileName + " : " + fileSize + "</div>");
                        }
                    }

                    drawFileList(data.importFiles);
                });
            },
            cleanImportDialogProcess: function () {
                components.spn_tolerance_import_processbar.removeClass("progress-bar-danger").removeClass("progress-bar-success").css('width', '0%').attr("aria-valuenow", 0);
                components.spn_tolerance_import_logArea.empty();
                components.spn_tolerance_import_status.empty();
                $('#spn_tolerance_import_operator').html($.i18n.prop('DATAIMPORT_ON_OPERATING', 0));
            },
            cleanImportDialogForm: function () {
                components.fle_tolerance_import_file.val("");
                components.btn_tolerance_import_submit.show();
                components.btn_tolerance_import_gobackTo1.hide();
                components.alt_tolerance_import_msgbar.hide();
            },
            checkImportFile: function (callback) {
                var path = components.fle_tolerance_import_file.val();
                var fileNames = [];
                $.each(data.importFiles, function (i, obj) {
                    fileNames.push(obj.name);
                });
                var param = {
                    search_originalName: JSON.stringify(fileNames),
                    search_projectId: components.slt_tolerance_import_project.select2("val"),
                    search_dcId: components.slt_tolerance_import_dc.val()
                };
                testDataM.checkImportFile(param, function (d) {
                    if ($.isFunction(callback)) {
                        callback(d);
                    }
                });
            },
            initSocket: function () {
                var soltkey = Math.floor(Math.random(10) * 1000000);
                components.txt_tolerance_import_soltkey.val(soltkey);
                var ws = socketBiz.initImport(soltkey, that.socketCallback);
                data.ws.sockjs = ws.sockjs;
                data.ws.stomp = ws.stomp;
            },
            cleanSocket: function () {
                if (data.ws.stomp != null) {
                    data.ws.stomp.disconnect(function () {
                        data.ws.sockjs = null;
                        data.ws.stomp = null;
                        var queryParameter = appLocalStorage.getLocal(data.search_timeout_key_spc);
                        if (queryParameter != null) {
                            queryParameter = JSON.parse(queryParameter);
                            var timeout = queryParameter.timeout;
                            clearTimeout(timeout);
                        }
                    });
                }
            },
            socketCallback: function (pdata) {
                if (pdata.target == "SPC") {
                    var userId = globalM.getUserId();
                    socketBiz.receivedProcess(pdata, {
                        processbar: $("#spn_tolerance_import_processbar"),
                        pstatus: $('#spn_tolerance_import_status'),
                        poperator: $('#spn_tolerance_import_operator'),
                        plog: $('#spn_tolerance_import_logArea'),
                        psubmit: $('#btn_tolerance_import_submit'),
                        ptimeoutkey: appConst.searchKey.search_dataImport_timeout_key + userId
                    });
                }
            },
            //Import Button
            bindExportEvent: function (listener) {
                components.btn_tolerance_export.unbind('click');
                components.btn_tolerance_export.click(function (e) {
                    var param = that.getSchemeParameters();
                    if (param.usl == "" || param.lsl == "" || param.calculateTimes == "") {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_EMPTY") + "</font>";
                        return;
                    } else {
                        document.getElementById("param-label").innerHTML = "";
                    }
                    var regExp = /^[+-]?\d+(\.\d+)?$/;
                    if (!regExp.test(param.usl) || !regExp.test(param.lsl)) {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_INTEGER") + "</font>";
                        return;
                    } else {
                        document.getElementById("param-label").innerHTML = "";
                    }
                    var regExp1 = /^(0|\+?[1-9][0-9]*)$/;
                    if (!(regExp1.test(param.calculateTimes))) {
                        document.getElementById("param-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_POSITIVE_INTEGER") + "</font>";
                        return;
                    } else {
                        document.getElementById("param-label").innerHTML = "";
                    }
                    toleranceM.exportResult(param, function () {
                        msgBox.show({
                            content: "<span id='grr_export_message' style='font-size:15px;'><i class='fa fa-refresh fa-spin animated'></i> Exporting ... You can track the exporting progress in <a href='#exportfile/all' > Export History</a></span>",
                            type: "success",
                            timeout: 0
                        });
                    });
                    if ((typeof listener) == 'function') {
                        listener(searchFields);
                    }
                });
            }
        }
    });